package jianzhiOffer;

import java.util.Arrays;

//剑指 Offer 58 - I. 翻转单词顺序
public class Num58_I_reverseWords {
    public String reverseWords(String s) {
//        String[] words = s.trim().split(" ");
//        StringBuilder sb = new StringBuilder();
//        for (int i = words.length-1; i >= 0 ; i--) {
//            if (words[i].equals(" ") )continue;;
//            sb.append(words[i]+" ");
//        }
//        return sb.toString().trim();
        String[] strs = s.trim().split(" "); // 删除首尾空格，分割字符串
        StringBuilder res = new StringBuilder();
        for(int i = strs.length - 1; i >= 0; i--) { // 倒序遍历单词列表
            if(strs[i].equals("")) continue; // 遇到空单词则跳过
            res.append(strs[i] + " "); // 将单词拼接至 StringBuilder
        }
        return res.toString().trim(); // 转化为字符串，删除尾部空格，并返回


    }


}
